package com.aidex.biz.controller;

import com.aidex.biz.domain.Customer;
import com.aidex.biz.messageSend.MessageSendService;
import com.aidex.biz.service.*;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.redis.RedisCache;
import com.aidex.common.utils.StringUtils;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.system.service.ISysUserService;
import com.aidex.wxCompany.WxWrokMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController("ApiTestController")
@RequestMapping("/webApi/TestController")
public class TestController {
    @Autowired
    ZhuangkuLogService zhuangkuLogService;
    @Autowired
    MessageSendService messageSendService;
    @Autowired
    CustomerShadowInfoService customerShadowInfoService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private MessageInfoService messageInfoService;
    @Autowired
    private TempShareService tempShareService;
    @Autowired
    private PushRuleService pushRuleService;
    @Autowired
    private PushRuleUserService pushRuleUserService;
    @Autowired
    private BusinessSetService businessSetService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private WxWrokMessageService wxWrokMessageService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 将BufferedImage转换为Base64字符串
     *
     * @param image      要转换的图像
     * @param formatName 图像格式（如"png", "jpg"等）
     * @return Base64编码的字符串
     */
    public static String convertImageToBase64(BufferedImage image, String formatName)
            throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, formatName, baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    private static String getMD5(byte[] bytes) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] array = md.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : array) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    public Boolean drawStringToImage() {
        try {
            // 1. 读取原始图片
            BufferedImage originalImage = ImageIO.read(new File("/Users/zhouzhou/IdeaProjects/jxzr-crm-manage-sys/aidex-biz/src/main/java/com/aidex/biz/controller/goodNewsPic.jpg"));

            // 2. 创建可编辑的图像副本
            BufferedImage newImage = new BufferedImage(
                    originalImage.getWidth(),
                    originalImage.getHeight(),
                    BufferedImage.TYPE_INT_RGB);

            Graphics2D graphics = newImage.createGraphics();
            graphics.drawImage(originalImage, 0, 0, null);

            // 3. 设置文字属性
            graphics.setColor(Color.YELLOW); // 文字颜色
            graphics.setFont(new Font("微软雅黑", Font.BOLD, 100)); // 字体

            // 4. 添加/修改文字
            String newText = "测试-动态修改的文字";
            graphics.drawString(newText, 300, 200); // 文字位置(x,y)

            // 5. 释放资源并保存
            graphics.dispose();
            ImageIO.write(newImage, "jpg", new File("modified.jpg"));


            // 或者转换为JPG格式的Base64
            String robot = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=468d3ed3-5b78-4c1a-aab5-fb05e66b1e6c";
            String base64JPG = convertImageToBase64(newImage, "jpg");


            // 1. 将图片转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(newImage, "jpg", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);

            // 2. 获取图片的MD5值
            String md5 = getMD5(imageBytes);
            System.out.println("图片文字修改完成！");
            return wxWrokMessageService.sendImageMessageFromRobotToGroup(robot, base64Image, md5);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * testWebSocket
     *
     * @return
     */
    @PostMapping("/testSendWxMsg")
    public R testSendWxMsg() {
        return R.status(this.drawStringToImage());
    }


    /**
     * testWebSocket
     *
     * @return
     */
    @PostMapping("/testSendMsg")
    public R testSendMsg(@RequestBody String phone) {
        Customer customerInfo = customerService.findCustomerByphone(phone);


        String companyName = "南昌分公司";
        String cusName = Objects.toString(customerInfo.getCusName(), "");
        String carNo = Objects.toString(customerInfo.getCarNo(), "");
        String pgPrice = Objects.toString(customerInfo.getPgPrice(), "");
        String mileage = Objects.toString(customerInfo.getMileage(), "");
        String fuckCarNoTime = Objects.toString(customerInfo.getFuckCarNoTime(), "");
        String carStatus = Objects.toString(customerInfo.getCarStatus(), "");
        String amount = Objects.toString(customerInfo.getAmount(), "");
        String zx = Objects.toString(customerInfo.getZx(), "");
        String shadow = Objects.toString("测试测试", "");
        String toHomeTime = Objects.toString("2025-6-30 11:00:00", "");
        String userName = Objects.toString("系统管理员", "");//SecurityUtils.getLoginUser().getUser().getName();


        String wxMsgModel = ConfigUtils.getConfigValueByKey("wxWork.model.toHome.new");
        if (StringUtils.isNotNull(wxMsgModel)) {
            String content = String.format(wxMsgModel.replace("\\n", "\n"),
                    companyName,
                    cusName,
                    carNo,
                    pgPrice,
                    mileage,
                    fuckCarNoTime,
                    carStatus,
                    amount,
                    zx,
                    shadow,
                    toHomeTime,
                    userName
            );
            SysUser sysUser = new SysUser();
            sysUser.setPhonenumber("@all");//艾特所有人
            String robotAddress = ConfigUtils.getConfigValueByKey("tencent.wxWork.address.connect");
            messageSendService.sendMessageWxWorkToGroup(robotAddress, content, new String[]{sysUser.getPhonenumber()});
            return R.status(true);
        }
        return R.status(false);
    }

    /**
     * 线索推送测试
     *
     * @param
     */
    @PostMapping("/tesSavePushCustomer")
    public void testSavePushCustomer(@RequestBody String phone) {
        Customer customer = customerService.findCustomerByphone(phone);
        customerService.savePushCustomer(customer);
    }

    @PostMapping("/testZhuangku")
    public void testZhuangku(@RequestBody String phone) {
        String laiyuan = "橙易通A";
        Customer customer = new Customer();
        customer.setPhone(phone);
        List<Customer> customers = customerService.findList(customer);
        for (Customer cus : customers) {
            customerService.updateStatusIfExistedAfterCheck(cus, laiyuan, phone, customers.size());
        }
    }

    /**
     * 同步企微userid
     *
     * @param
     */
    @PostMapping("/tesGetAllWxUserIds")
    public R tesGetAllWxUserIds() {
        try {
            SysUser sysUser = new SysUser();
            List<SysUser> list = sysUserService.findList(sysUser);
            for (SysUser user : list) {
                if (StringUtils.isNotNull(user.getPhonenumber())) {
                    Map<String, Object> result = wxWrokMessageService.getUserIdByPhone(user.getPhonenumber());
                    if ((boolean) result.get("isSuccess")) {
                        // 同步到用户表
                        user.setUserPinyin(result.get("userId").toString());
                        sysUserService.updateUserPinyin(user);
                    }
                }
            }
            return R.status(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/testRefreshRedisCache")
    public R testRefreshRedisCache() {
        boolean is = redisCache.deleteKey("company:" + "29040ebdb82944ae92584e46339e176a");
        return R.status(is);
    }


}
